package com.ihrm.system.service.Impl;

import com.ihrm.common.utils.IdWorker;
import com.ihrm.common.utils.QRCodeUtil;
import com.ihrm.domain.system.User;
import com.ihrm.domain.system.response.FaceLoginResult;
import com.ihrm.domain.system.response.QRCode;
import com.ihrm.system.service.FaceLoginService;
import com.ihrm.system.service.UserService;
import com.ihrm.system.utils.BaiduAiUtil;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class FaceLoginServiceImpl implements FaceLoginService {
    @Value("${qr.url}")
    private String url;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private QRCodeUtil qrCodeUtil;

    @Autowired
    private BaiduAiUtil baiduAiUtil;

    @Autowired
    private UserService userService;

    //创建二维码
    public QRCode getQRCode() throws IOException {
        String code = new IdWorker().nextId() + "";
        FaceLoginResult result = new FaceLoginResult("-1");
        redisTemplate.boundValueOps(getCacheKey(code)).set(result, 30,
                TimeUnit.MINUTES);
        String image = qrCodeUtil.crateQRCode(url + "?code=" + code);
        System.out.println(url + "?code=" + code);
        return new QRCode(code, image);
    }

    //根据唯一标识，查询用户是否登录成功
    public FaceLoginResult checkQRCode(String code) {
        String cacheKey = getCacheKey(code);
        FaceLoginResult result = (FaceLoginResult)
                redisTemplate.opsForValue().get(cacheKey);
        return result;
    }

    //扫描二维码之后，使用拍摄照片进行登录
    public String loginByFace(String code, MultipartFile attachment) throws IOException {
        String userId =
                baiduAiUtil.faceSearch(Base64Utils.encodeToString(attachment.getBytes()));
        FaceLoginResult result = new FaceLoginResult("1");
        if (userId != null) {
            User user = userService.selectById(userId);
            if (user != null) {
//                Subject subject = SecurityUtils.getSubject();
//                subject.login(new UsernamePasswordToken(user.getMobile(),
//                        user.getPassword()));
//                String token = subject.getSession().getId() + "";
//                result = new FaceLoginResult("0", token, userId);

                HttpClient httpClient = new HttpClient();
                PostMethod postMethod = new PostMethod("http://localhost:9002/sys/login");
                postMethod.addRequestHeader("accept", "*/*");
                postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                //添加请求参数
                Map paraMap = new HashMap();
                paraMap.put("mobile", user.getMobile());
                paraMap.put("password", "123456");
                String result1 = "";
                try {
                    int code1 = httpClient.executeMethod(postMethod);
                    if (code1 == 200){
                        result1 = postMethod.getResponseBodyAsString();
                        System.out.println("result:" + result1);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        redisTemplate.boundValueOps(getCacheKey(code)).set(result, 30,
                TimeUnit.MINUTES);
        return userId;
    }

    //构造缓存key
    public String getCacheKey(String code) {
        return "qrcode_" + code;
    }
}
